import {Component, OnInit, ViewChild, Input} from "@angular/core";
import {FormBuilder, FormGroup, Validators} from "@angular/forms";
import "datatables";
import "select2";
import {DataTablesComponent, DataTablesComponentConfig} from "app/theme/components/dataTables";
import {ModalDirective} from "ng2-bootstrap/ng2-bootstrap";
import {ExamSubmitInfo} from "./exam-submit.class";
import {EAService} from "./ea.service";
import {validateEmail} from '../../validators/email.validator';
import {races} from '../../../constants/races';
import {politicalStatuses} from '../../../constants/politicalStatuses';
import {provinces} from '../../../constants/provinces';
import {educations} from '../../../constants/educations';
import {technicaltitles} from '../../../constants/technicaltitles';

@Component({
  selector: 'ea',
  templateUrl: 'ea.component.html',
  styleUrls: ['ea.component.scss'],
  providers: [EAService]
})
export class EAComponent implements OnInit {
  @Input() type: string;
  @ViewChild('applyModal') applyModal: ModalDirective;
  @ViewChild('apprReviewModal') apprReviewModal: ModalDirective;
  @ViewChild('applyUpdateModal') applyUpdateModal: ModalDirective;
  @ViewChild('apprDeleteModal') apprDeleteModal: ModalDirective;
  @ViewChild(DataTablesComponent) dataTable: DataTablesComponent;

  private searchForm: ApplictionSearchForm = new ApplictionSearchForm();
  public userInfo: UserInfo = new UserInfo();

  private applyForm: FormGroup;
  private updateForm: FormGroup;
  private userForm:FormGroup;

  private userinfoUrl = '/water/userInfoSub/showOriginalInfo';
  private userinfoOfCompUrl = '/water/userInfoSub/showOriginalInfo';
  private applyUrl = '/water/certificateSub/add';
  private applyUserUrl = '/water/certificateSub/addApply';
  private applyUpdateUrl = '/water/certificateSub/update';
  private applyTableUrl = '/water/certificateSub';
  private apprDeleteUrl = '/water/certificate/delete';

  private disableUpload: boolean = false;
  private fileUploadUrl = '/platform/doc/upload';
  private idCardPic = 'idCardPic';
  private userPhoto = 'userPhoto';
  private proofEA = 'proofEA';
  private educationDoc = 'educationDoc';
  private sizeLimit = 2097152;
  private sizeLimitUserPhoto = 1500000;

  private apprBatchDownloadUrl = '/water/certificateSub/printApplySummaryTabs';
  private apprDownloadUrl = ' /water/certificateSub/printApplyTab';
  private apprInfoUrl = '/water/certificateSub/edit';

  private batchDownloadUrl: string = '';
  private disableBatchDownloadBtn = true;
  private disableDownloadBtn = true;
  private disableReviewBtn = true;
  private disableUpdateBtn = true;
  private applying = true; // only one same upload component is allowed here so control it by this variable.
  private disableDeleteBtn = true;
  private addUserInfo = false;
  private disableApplyBtn = false;

  private downloadUrl: string = '';

  private applyData: any = new ExamSubmitInfo();
  private applyInData: any = new ExamSubmitInfo();
  private applyDetailData: any = new ExamSubmitInfo();
  private applyPersonData: any = new ExamSubmitInfo();
  private updateData: any = new ExamSubmitInfo();
  private updatePersonData: any = new ExamSubmitInfo();
  private registerInfo: any = {};

  private _errorMsg: string;
  private errorShow = false;

  private dataTablesConfig: DataTablesComponentConfig = new DataTablesComponentConfig();

  public races = races;
  public provinces = provinces;
  public politicalStatuses = politicalStatuses;
  public educations = educations;
  public allTechnicaltitle = technicaltitles;

  private name: string = '';
  private idcard: string = '';
  private birthday: string = '';
  private education: string = '';
  private technicaltitles: string = '';

  private applyModalDisplay = true;
  private updateModalDisplay = true;

  private formErrors = {
    'userInfoSub_email': '',
    'userInfoSub_name': '',
    'userInfoSub_sex': '',
    'userInfoSub_idcard': '',
    'userInfoSub_birthday': '',
    'userInfoSub_folk': '',
    'userInfoSub_telephone': '',
    'userInfoSub_postcode': '',
    'userInfoSub_address': '',
    'userInfoSub_addressinfo': '',
    'userInfoSub_schoolname': '',
    'userInfoSub_speciality': '',
    'userInfoSub_education': '',
    'userInfoSub_technicaltitles': '',
  };

  private validationMessages = {
    'userInfoSub_email': {
      'validateEmail': '邮箱格式不正确'
    },

    'userInfoSub_name': {
      'required': '请填写姓名.',
      'minlength': '姓名至少4个字符长.',
      'maxlength': '姓名不能超过24个字符.'
    },

    'userInfoSub_sex': {
      'required': '请选择性别.',
    },

    'userInfoSub_idcard': {
      'required': '请填写身份证.',
    },

    'userInfoSub_birthday': {
      'required': '请填写出生日期.',
    },

    'userInfoSub_folk': {
      'required': '请选择民族.',
    },

    'userInfoSub_telephone': {
      'required': '请填写电话号码.',
      'minlength': '电话号码至少8个字符长.',
      'maxlength': '电话号码不能超过11个字符.'
    },

    'userInfoSub_postcode': {
      'required': '请填写邮编.'
    },
    'userInfoSub_address': {
      'required': '请填写地址.'
    },
    'userInfoSub_addressinfo': {
      'required': '请填写详细地址.'
    },
    'userInfoSub_schoolname': {
      'required': '请填写毕业学校.'
    },

    'userInfoSub_speciality': {
      'required': '请填写专业.'
    },
    'userInfoSub_education': {
      'required': '请填写学历.'
    },
    'userInfoSub_technicaltitles': {
      'required': '请填写技术职称.'
    }
  };


  constructor(private _fb: FormBuilder, private _service: EAService) {
  }

  ngAfterViewInit() {
    this.configApplyForm();
  }

  ngOnInit() {
    this.buildForm();
    this.buildUpdateForm();
    if (this.type === 'company') {
      this.initDatatablesComp();
      this.buildUserForm();
    } else {
      this.initDatatablesUser();
    }
  }

  clearModal(){
    this._errorMsg = null;
    this.applyPersonData = new ExamSubmitInfo();
    this.buildUserForm();
  }

  buildForm(): void {
    this.applyForm = this._fb.group(
      {
        'certificateSub_type': ['', [Validators.required]]
      }
    );

    this.applyForm.valueChanges
      .subscribe(data => this.onValueChanged(data));

    this.onValueChanged(); // (re)set validation messages now
  }

  buildUpdateForm(): void {
    this.updateForm = this._fb.group(
      {
        'type': [this.updatePersonData.certificate.type, [Validators.required]]
      }
    );

    this.updateForm.valueChanges
      .subscribe(data => this.onValueChanged(data));

    this.onValueChanged(); // (re)set validation messages now
  }

  buildUserForm(): void {
    this.userForm = this._fb.group(
      {
        'userInfoSub_email': [this.userInfo.userInfoSub_email, [
          validateEmail
        ]],
        'userInfoSub_name': [this.userInfo.userInfoSub_name, [
          Validators.required
        ]],
        'userInfoSub_sex': [this.userInfo.userInfoSub_sex, [
          Validators.required
        ]],
        'userInfoSub_address': [this.userInfo.userInfoSub_address, [
          Validators.required
        ]],
        'userInfoSub_addressinfo': [this.userInfo.userInfoSub_addressinfo, [
          Validators.required
        ]],
        'userInfoSub_province': [this.userInfo.userInfoSub_province],
        'userInfoSub_folk': [this.userInfo.userInfoSub_folk, [
          Validators.required
        ]],
        'userInfoSub_government': [this.userInfo.userInfoSub_government],
        'userInfoSub_idcard': [this.userInfo.userInfoSub_idcard, [
          Validators.required
        ]],

        'userInfoSub_postcode': [this.userInfo.userInfoSub_postcode, [
          Validators.required,
        ]],
        'userInfoSub_schoolname': [this.userInfo.userInfoSub_schoolname, [
          Validators.required
        ]],
        'userInfoSub_speciality': [this.userInfo.userInfoSub_speciality, [
          Validators.required
        ]],
        'userInfoSub_telephone': [this.userInfo.userInfoSub_telephone, [
          Validators.required,
          Validators.minLength(8),
          Validators.maxLength(11)]],
        'userInfoSub_education': [this.registerInfo.userInfoSub_education],
        'userInfoSub_technicaltitles': [this.registerInfo.userInfoSub_technicaltitles],
      }
    );
    this.userForm.valueChanges
      .subscribe(data => this.onValueChanged(data));

    this.onValueChanged(); // (re)set validation messages now
  }

  onValueChanged(data?: any) {
    if (!this.userForm) { return; }
    const form = this.userForm;
    for (const field in this.formErrors) {

      this.formErrors[field] = '';
      const control = form.get(field);

      if (control && control.dirty && !control.valid) {
        const messages = this.validationMessages[field];
        for (const key in control.errors) {
          this.formErrors[field] += messages[key] + ' ';
        }
      }
    }
  }

  private initDatatablesUser() {
    this.dataTablesConfig.ajaxUrl = this.applyTableUrl;
    this.dataTablesConfig.selectable = 'single';
    this.dataTablesConfig.columnsDef = [
      {'name': '姓名', 'id': 'name'},
      {'name': '性别', 'id': 'sex'},
      {'name': '身份证', 'id': 'idcard'},
      {'name': '职称', 'id': 'technicaltitles'},
      {'name': '出生日期', 'id': 'birthday'},
      {'name': '学历', 'id': 'education'},
      {'name': '证书类型', 'id': 'type'},
      {'name': '提交时间', 'id': 'submittime', 'orderable': true},
      {'name': '审批时间', 'id': 'verifytime', 'orderable': true},
      {'name': '状态', 'id': 'verified'}
    ];
  }

  private initDatatablesComp() {
    this.dataTablesConfig.ajaxUrl = this.applyTableUrl;
    this.dataTablesConfig.columnsDef = [
      {'name': '姓名', 'id': 'name'},
      {'name': '性别', 'id': 'sex'},
      {'name': '身份证', 'id': 'idcard'},
      {'name': '职称', 'id': 'technicaltitles'},
      {'name': '出生日期', 'id': 'birthday'},
      {'name': '学历', 'id': 'education'},
      {'name': '证书类型', 'id': 'type'},
      {'name': '提交时间', 'id': 'submittime', 'orderable': true},
      {'name': '审批时间', 'id': 'verifytime', 'orderable':true},
      {'name': '状态', 'id': 'verified'}
    ];
  }

  tableRowSelect(rowData: any[]) {
    this.disableAllButtons();
    if (rowData.length > 0) {
      this.disableReviewBtn = rowData.length !== 1;
      this.disableApplyBtn = true;
      this.disableBatchDownloadBtn  = rowData[0].verified !== '待审核';
      this.disableUpdateBtn = !(rowData.length === 1 && rowData[0].verified === '未提交');
      if (!this.disableBatchDownloadBtn) {
        this.batchDownloadUrl = this.apprBatchDownloadUrl + '?ids=' + rowData[0].ids;
        for (let i = 1; i < rowData.length; i++) {
          let data = rowData[i];
          this.batchDownloadUrl = this.batchDownloadUrl + ',' + data.ids;
        }
      }
    }
    this.disableDownloadBtn = rowData.length !== 1 || rowData[0].verified !== '待审核';
    if (!this.disableDownloadBtn) {
      this.downloadUrl = this.apprDownloadUrl + '?ids=' + rowData[0].ids;
    }
    this.disableDeleteBtn = !(rowData.length === 1 && rowData[0].verified === '未通过');
    this.applyData = rowData;
  }

  handleError(e:any){
    if(e.type == 'error'){
      this.errorShow = true;
    }
  }

  private disableAllButtons() {
    this.disableReviewBtn = this.disableBatchDownloadBtn = this.disableUpdateBtn = this.disableDeleteBtn = true;
    this.disableApplyBtn = false;
  }

  review() {
    let pkid = this.applyData[0].pkid;
    this.loadInfo(pkid);
    this.apprReviewModal.show();
  }

  private loadInfo(pkid: string) {
    this.applyDetailData = new ExamSubmitInfo();
    this._service.reviewAppr(this.apprInfoUrl, pkid)
      .then(res => {
        if (res.status === 'success') {
          this.applyDetailData = res.data;
        } else {
          this._errorMsg = res.data ? res.data : '网络错误';
        }
      }, error => {
        this._errorMsg = error;
      });
  }

  update() {
    this.clearModal();
    this.applying = false;
    this.updateModalDisplay = true;
    this.updateData = new ExamSubmitInfo();
    this.updateData.pkid = this.applyData[0].pkid;
    this.loadUpdateInfo(this.updateData.pkid);
  }

  private loadUpdateInfo(pkid: string) {
    this.updatePersonData = new ExamSubmitInfo();
    this._service.reviewAppr(this.apprInfoUrl, pkid)
      .then(res => {
        if (res.status === 'success') {
          this.updatePersonData = res.data;
          this.buildUpdateForm();
          this.applyUpdateModal.show();
        } else {
          this._errorMsg = res.data ? res.data : '网络错误';
        }
      }, error => {
        this._errorMsg = error;
      });
  }

  updateApply(action:string){

    let updatedata = this.updateForm.value;
    this.updateData.type = updatedata.type;
    this.updateData.action = action;

    this._service.submitUpdate(this.applyUpdateUrl, this.updateData)
      .then(res => {
        if (res.status === "success") {
          this.applyUpdateModal.hide();
          this.dataTable.draw();
        } else {
          this._errorMsg = res.data ? res.data : '网络错误';
        }
      }, error => {
        this._errorMsg = error;
      });
  }

  public onSubmit(action:string): void {
    let url = "";
    let applydata = this.applyForm.value;
    this.applyInData.certificateSub_type = applydata.certificateSub_type;
    if (this.type === 'company') {
      url=this.applyUrl;
      if(this.addUserInfo === true){
        let formData = this.userForm.value;
        this.registerInfo = Object.assign(this.registerInfo, formData);
        this.applyInData = Object.assign(this.applyInData, this.registerInfo);
        this.applyInData.userid = null;
      }else{
        let userList: any = document.getElementById('userList');
        let index = userList.selectedIndex;
        this.applyInData.userid = userList.options[index].value;
      }
    }else{
      url = this.applyUserUrl;
    }
    this.applyInData.action = action;
    this._service.submit(url, this.applyInData)
      .then(res => {
        if (res.status === "success") {
          this._errorMsg = '';
          this.apprApplyClose();
          this.dataTable.draw(false);
        } else {
          this._errorMsg = res.data ? res.data : '网络错误';
        }
      }, error => {
        this._errorMsg = error;
      });
  }

  private addApply(): void {
    this.clearModal();
    if(this.type === 'company'){
      this.initSelect2();
    }else if(this.type === 'user'){
      this.getUserName();
    }
    this.applyModalDisplay = true;
    this.applyModal.show();
    this.applying = true;
  }

  search() {
    this.dataTable.draw();
  }

  onFileUploading() {
    this.disableUpload = true;
  }

  onFinishUploading(replyObj: any) {
    this.applyInData[replyObj.property] = replyObj.rsp.data[0].ids;
    this.applyData[replyObj.property] = replyObj.rsp.data[0].ids;
    this.disableUpload = false;
  }

  onFinishUploadingUpdate(replyObj: any) {
    this.updateData[replyObj.property] = replyObj.rsp.data[0].ids;
    this.disableUpload = false;
  }

  showDeleteModal() {
    this.apprDeleteModal.show();
  }

  onHideModal(): void {
    this.applyModalDisplay = false;
    this.updateModalDisplay = false;
    jQuery(".modal-backdrop").remove();
  }


  updateDateRange(event) {
    this.searchForm.startdate = this.date2String(event.beginDate);
    this.searchForm.enddate = this.date2String(event.endDate);
  }

  updateUserDate(event, type:string) {
    this.registerInfo[type] = this.date2String(event.date);
  }

  private date2String(date: any): string {
    if (Object.keys(date).length === 0 || date === null || date === undefined || (date.year == 0&&date.month==0&&date.day==0)) {
      return null;
    }

    let str = date.year + '-';
    if (date.month < 10) {
      str += '0';
    }
    str += date.month + '-';

    if (date.day < 10) {
      str += '0';
    }
    str += date.day;
    return str;
  }

  public delete():void{
    let pkids = [];
    for (let row of this.applyData) {
      pkids.push(row.pkid);
    }
    this._service.deleteAppr(this.apprDeleteUrl, pkids)
      .then(res => {
        if (res.status === 'success') {
          this.apprDeleteModal.hide();
          this.dataTable.draw(false);
          this.disableDeleteBtn = true;
        } else {
          this._errorMsg = res.data ? res.data : '网络错误';
        }
      }, error => {
        this._errorMsg = error;
      });
  }

  public apprDeleteClose() {
    this._errorMsg = null;
    this.apprDeleteModal.hide();
  }

  public apprApplyClose(){
    this._errorMsg = null;
    this.applyModalDisplay = false;
    this.applyModal.hide()
  }

  public applyUpdateClose(){
    this._errorMsg = null;
    this.updateModalDisplay = false;
    this.applyUpdateModal.hide()
  }

  private configApplyForm(): void {
    if (this.type === 'company') {
      this.initSelect2();
    } else {
      this.getUserName();
    }
  }

  private initSelect2() {
    let data: any = [];
    this._service.getEmpolyeesInfo().then(employees => {

      for (let i = 0; i < employees.length; i++) {
        let item: any = {};
        item.id = employees[i].ids;
        item.text = employees[i].name + '-' + employees[i].idcard;
        data.push(item);
      }

      jQuery('#userList').select2({
        data: data
      });
    });
  }

  private getUserName() {
    this._service.getUserinfo(this.userinfoUrl)
      .then(res => {
        if (res.status === 'success' && res.data) {
          this.applyPersonData = res.data;
        } else {
        }
      });
  }

  getUserForComp() {
    this.addUserInfo = false;
    this.applyPersonData = new ExamSubmitInfo();
    let userList: any = document.getElementById('userList');
    this._service.getUserInfoOfCompany(this.userinfoOfCompUrl, userList.value)
      .then(res => {
        if (res.status === "success") {
          this.applyPersonData = res.data;
        } else {
          this._errorMsg = res.data ? res.data : '网络错误';
        }
      }, error => {
        this._errorMsg = error;
      });
  }

  addUser() {
    this.addUserInfo = true;
    this.buildUserForm();
  }
}

export class ApplictionSearchForm {
  public idcard: string = '';
  public name: string = '';
  public type: string = '';
  public verified: string = '待审核';
  public birthday: string = '';
  public education: string = '';
  public technicaltitles: string = '';
  public enddate: string = '';
  public startdate: string = '';
}

export class UserInfo {
  // 账号信息
  password: string;
  passwordRepeat: string;
  // 用户信息
  userInfoSub_address: string;
  userInfoSub_addressinfo: string;
  userInfoSub_birthday: string;
  userInfoSub_province: string;
  userInfoSub_finishschooldate: string;
  userInfoSub_government: string;
  userInfoSub_idcard: string;
  userInfoSub_name: string;
  userInfoSub_email: string;
  userInfoSub_postcode: string;
  userInfoSub_schoolname: string;
  userInfoSub_sex: string;
  userInfoSub_speciality: string;
  userInfoSub_telephone: string;
  userInfoSub_folk: string;
  userInfoSub_education: string;
  userInfoSub_technicaltitles: string;
}
